/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package siswa;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.beans.PropertyVetoException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JDesktopPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Rendra
 */
public class LoadDataset extends javax.swing.JInternalFrame {
    public static ClassLoader loader =  Siswa.class.getClassLoader();
    private DefaultComboBoxModel cbModel;
    private DefaultTableModel tbModel;
    private String tahun;
    private String destPath;
    
    /**
     * Creates new form LoadDataset
     */
    public LoadDataset() {
        initComponents();
        fetchComboBox();
        loadDataSiswa(tahun);
    }
    
    private void fetchComboBox() {
        try {
            Statement stmt = App.conn.createStatement();            
            ResultSet rs = stmt.executeQuery("SELECT DISTINCT(b.tahun_lulus) FROM lulusan a " +
            "RIGHT JOIN siswa b ON a.tahun_lulus = b.tahun_lulus");
            Vector data = new Vector();
            while (rs.next()) {
                data.add(rs.getString("tahun_lulus"));
            }
            cbModel = new DefaultComboBoxModel(data);
            ComboThn.setModel(cbModel);
            tahun = ComboThn.getSelectedItem().toString();
        } catch (SQLException ex) {
            Logger.getLogger(Criteria.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void loadDataSiswa(String thn) {
        try {
            Statement stmt = App.conn.createStatement();
            String qry = "SELECT a.id_siswa AS ID, a.nama_siswa AS \"NAMA LENGKAP\", "+
                    "a.n_uan AS UAN, a.n_keterampilan AS KETR, " +
                    "(CASE WHEN a.n_kelamin > 1 THEN 'L' ELSE 'P' END) AS JK, " +
                    "(CASE WHEN a.n_pekerjaan > 2 THEN 'PNS' WHEN a.n_pekerjaan > 1 "+
                    "THEN 'Karyawan Swasta' ELSE 'Lainnya' END) AS \"PEKERJAAN WALI\", " +
                    "a.n_gaji AS \"GAJI WALI\", b.v_uan AS N1, "+
                    "b.v_keterampilan AS N2, b.v_kelamin AS N3, " +
                    "b.v_pekerjaan AS N4, b.v_gaji AS N5, a.tujuan_sekolah AS TUJUAN " +
                    "FROM siswa a " +
                    "LEFT JOIN siswa_detil b ON b.id_siswa = a.id_siswa "+
                    "WHERE a.tahun_lulus = '"+thn+"'";
            stmt.executeQuery(qry);
            ResultSet rs = stmt.getResultSet();
            ResultSetMetaData md = rs.getMetaData();
            int columns = md.getColumnCount();
            
            Vector data = new Vector(columns);
            Vector rows = new Vector(columns);
            Vector name = new Vector(columns);
            
            StringBuilder prop = new StringBuilder();
            prop.append("attributes = UN, Keterampilan, Kelamin, Pekerjaan, Gaji\n");
            prop.append("categories = SMA, SMK\n\n");
            prop.append("UN = A, B, C\n");
            prop.append("Keterampilan = A, B, C\n");
            prop.append("Kelamin = L, P\n");
            prop.append("Pekerjaan = A, B, C\n");
            prop.append("Gaji = A, B, C, D\n\n");
            prop.append("examples : \\\n");

            int k = 0;
            while (rs.next()) {
                if (k == 0) {
                    for (int i=1;i<=columns;i++) {
                        name.addElement(md.getColumnLabel(i));
                    }
                }
                String elements = "";
                for (int j=1;j<=columns;j++) {
                    rows.addElement(rs.getObject(j));
                    if (j>=8)
                        elements += rs.getObject(j) + ", ";
                }
                elements = elements.substring(0, elements.length()-2);
                prop.append("\t\t<").append(elements).append("> \\\n");
                
                data.addElement(rows);
                rows = new Vector(columns);
                
                String tujuan_sek = rs.getString("TUJUAN");
                App.common.addJumlahTujuan(tujuan_sek);
                k++;
            }
            
            String new_prop = prop.toString().substring(0, prop.length()-3);
            destPath = this.getClass().getResource("/siswa").toString().replace("file:/", "").replace("%20", " ");
            App.common.setWorkDir(destPath);
                
            try {
                App.common.writeTextFile(new_prop, destPath+"/siswa.properties");
            } catch (IOException ex) {
                Logger.getLogger(LoadDataset.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            tbModel = new DefaultTableModel(data, name);
            SiswaTable.setModel(tbModel);
            SiswaTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            int gapWidth = 10;
            int gapHeight = 5;
            SiswaTable.setIntercellSpacing(new Dimension(gapWidth, gapHeight));
            SiswaTable.setRowHeight(20);
            SiswaTable.getTableHeader().setFont(new Font(null, Font.BOLD, 12));            
            ListSelectionModel selectionModel = SiswaTable.getSelectionModel();
            selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            
            /**
             * -- Optional
             * Set column width
             */
            SiswaTable.getColumnModel().getColumn(0).setPreferredWidth(35);
            SiswaTable.getColumnModel().getColumn(1).setPreferredWidth(225);
            SiswaTable.getColumnModel().getColumn(2).setPreferredWidth(50);
            SiswaTable.getColumnModel().getColumn(3).setPreferredWidth(50);
            SiswaTable.getColumnModel().getColumn(4).setPreferredWidth(50);
            SiswaTable.getColumnModel().getColumn(5).setPreferredWidth(120);
            SiswaTable.getColumnModel().getColumn(6).setPreferredWidth(80);
            SiswaTable.getColumnModel().getColumn(7).setPreferredWidth(60);
            SiswaTable.getColumnModel().getColumn(8).setPreferredWidth(30);
            SiswaTable.getColumnModel().getColumn(9).setPreferredWidth(30);
            SiswaTable.getColumnModel().getColumn(10).setPreferredWidth(30);
            SiswaTable.getColumnModel().getColumn(11).setPreferredWidth(30);
            SiswaTable.getColumnModel().getColumn(12).setPreferredWidth(30);
        } catch (SQLException ex) {
            Logger.getLogger(Criteria.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        CalcBtn = new javax.swing.JButton();
        ComboThn = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        TableScroll = new javax.swing.JScrollPane();
        SiswaTable = new javax.swing.JTable();

        CalcBtn.setText("Kalkulasi");
        CalcBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CalcBtnActionPerformed(evt);
            }
        });

        ComboThn.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                ComboThnItemStateChanged(evt);
            }
        });

        jLabel1.setText("Data Tahun : ");

        SiswaTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        TableScroll.setViewportView(SiswaTable);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ComboThn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(CalcBtn)
                .addContainerGap())
            .addComponent(TableScroll, javax.swing.GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(TableScroll, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CalcBtn)
                    .addComponent(ComboThn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void ComboThnItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_ComboThnItemStateChanged
        // TODO add your handling code here:
        tahun = ComboThn.getSelectedItem().toString();
        tbModel.setRowCount(0);
        loadDataSiswa(tahun);
    }//GEN-LAST:event_ComboThnItemStateChanged

    private void CalcBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CalcBtnActionPerformed
        HypothesisSpace hs = new HypothesisSpace();
        hs.loadFromFile("siswa/siswa.properties");
        ID3Node id3 = ID3.getNode(hs, hs.examples, hs.attributes, null);
        
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(baos);
        PrintStream old = System.out;
        System.setOut(ps);
        System.out.println(id3);
        System.out.flush();
        System.setOut(old);
        String xml = baos.toString();
        
        try {
            App.common.writeTextFile(xml, destPath+"/siswa.xml");
        } catch (IOException ex) {
            Logger.getLogger(LoadDataset.class.getName()).log(Level.SEVERE, null, ex);
        }

        JDesktopPane desk = this.getDesktopPane();
        desk.removeAll();
        desk.repaint();
        SiswaTree frm = new SiswaTree();
        desk.add(frm);
        frm.setVisible(true);
        frm.setBorder(null);
        try {
            frm.setMaximum(true);
            ((javax.swing.plaf.basic.BasicInternalFrameUI)frm.getUI()).setNorthPane(null);
            frm.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.LIGHT_GRAY));
        } catch (PropertyVetoException pvx) {
            Logger.getLogger(Siswa.class.getName()).log(Level.SEVERE, null, pvx);
        }
    }//GEN-LAST:event_CalcBtnActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton CalcBtn;
    private javax.swing.JComboBox ComboThn;
    private javax.swing.JTable SiswaTable;
    private javax.swing.JScrollPane TableScroll;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration//GEN-END:variables
}
